﻿using System;
using MTBrainStorm.Models.VirtualKeyboard.VirtualKeyCodes;

namespace MTBrainStorm.Models.VirtualKeyboard
{
    public class VirtualKeyboardModel
    {
        private readonly byte[] _keyboardState = new byte[256];

        public IntPtr KeyboardLayout { get; private set; }

        public IntPtr[] LayoutList { get; private set; }
        
        public bool IsShiftDown
        {
            get
            {
                return _keyboardState[(int) Specials.Shift] == 128;
            }
            private set
            {
                if (value)
                    _keyboardState[(int) Specials.Shift] = 128;
                else
                    _keyboardState[(int)Specials.Shift] = 0;
            }
        }
        
        public bool IsAltGrDown
        {
            get
            {
                return _keyboardState[(int)Specials.Control] == 128 && _keyboardState[(int)Specials.Alt] == 128;
            }
            private set
            {
                if (value)
                {
                    _keyboardState[(int)Specials.Control] = 128;
                    _keyboardState[(int)Specials.Alt] = 128;
                }
                else
                {
                    _keyboardState[(int)Specials.Control] = 0;
                    _keyboardState[(int)Specials.Alt] = 0;
                }
            }
        }
        
        public bool IsCapsLockEnabled
        {
            get
            {
                return _keyboardState[(int)Specials.CapsLock] == 1;
            }
            set
            {
                if (value)
                    _keyboardState[(int)Specials.CapsLock] = 1;
                else
                    _keyboardState[(int) Specials.CapsLock] = 0;
            }
        }

        public VirtualKeyboardModel()
        {
            var nElements = NativeMethods.GetKeyboardLayoutList(0, null);
            LayoutList = new IntPtr[nElements];
            NativeMethods.GetKeyboardLayoutList(LayoutList.Length, LayoutList);

            KeyboardLayout = NativeMethods.GetKeyboardLayout(0); //get system-default keyboard layout
        }

        public char GetCharacter(Characters keyCode)
        {
            var chars = new char[1];
            NativeMethods.ToUnicodeEx((uint) keyCode, 0, _keyboardState, chars, chars.Length, 0, KeyboardLayout);
            return chars[0];
        }

        public void ShiftDown()
        {
            IsShiftDown = true;
        }

        public void ShiftUp()
        {
            IsShiftDown = false;
        }

        public void AltGrDown()
        {
            IsAltGrDown = true;
        }

        public void AltGrUp()
        {
            IsAltGrDown = false;
        }

        public void ToggleCapsLock()
        {
            IsCapsLockEnabled = !IsCapsLockEnabled;
        }
    }
}
